package com.idc.resource.manager;

import com.idc.resource.dal.dto.TCompanyFile;
import com.idc.resource.dal.dto.TCompanyInfo;
import com.idc.resource.dal.mapper.TCompanyFileMapper;
import com.idc.resource.dal.mapper.TCompanyInfoMapper;
import com.idc.resource.enums.ErrorCodeEnum;
import com.idc.resource.enums.ExitsFlagEnum;
import com.idc.resource.exception.IdcServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 企业信息管理
 * Created by Lijing on 2017/7/12.
 */
@Slf4j
@Component
public class CompanyManager {
    /** 企业基本资料 */
    @Autowired
    private TCompanyInfoMapper tCompanyInfoMapper;
    /** 企业证件扫描件 */
    @Autowired
    private TCompanyFileMapper tCompanyFileMapper;

    /**
     * 新注册企业信息
     * @param tCompanyInfo 企业信息
     * @param tCompanyFile 企业扫描件信息
     * @return 企业信息
     */
    public TCompanyInfo registerCompanyInfo(TCompanyInfo tCompanyInfo, TCompanyFile tCompanyFile){
        try {
            if(StringUtils.isBlank(tCompanyFile.getIspCer())){
                tCompanyInfo.setIspCer(ExitsFlagEnum.EXITS.getCode());
            }else {
                tCompanyInfo.setIspCer(ExitsFlagEnum.NO_EXITS.getCode());
            }
            int i = tCompanyInfoMapper.insert(tCompanyInfo);
            if(i!=1){
                log.error("新增企业信息失败，新增记录数:{}",i);
                throw new IdcServiceException(ErrorCodeEnum.DATA_ERROR.getCode(),ErrorCodeEnum.DATA_ERROR.getDesc());
            }
            tCompanyFile.setCompanyId(tCompanyInfo.getId());
            i = tCompanyFileMapper.insert(tCompanyFile);
            if(i!=1){
                log.error("新增企业扫描件信息失败，新增记录数:{}",i);
                throw new IdcServiceException(ErrorCodeEnum.DATA_ERROR.getCode(),ErrorCodeEnum.DATA_ERROR.getDesc());
            }
            return tCompanyInfo;
        }catch (IdcServiceException ide){
            throw ide;
        }catch (Exception e){
            log.error("新增企业信息失败，失败原因:",e);
            throw new IdcServiceException(ErrorCodeEnum.DB_ERROR.getCode(),ErrorCodeEnum.DB_ERROR.getDesc());
        }
    }

    /**
     * 根据企业id查询企业信息
     * @param id 企业id
     * @return 企业信息
     */
    public TCompanyInfo selectById(Long id){
        return tCompanyInfoMapper.selectByPrimaryKey(id);
    }
}
